<template>
  <el-dialog :destroy-on-close="true" :title="formData.id?'编辑部门':'新增部门'" :visible="dialogVisible" @close="btnCancel">
    <!-- 匿名插槽 -->
    <el-form ref="addDept" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @blur="checkManager">
          <el-option
            v-for="user in employeeList"
            :key="user.id"
            :label="user.username"
            :value="user.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>

  </el-dialog>
</template>

<script>
import { department, addDepartment, companyDepartment, getDepartment } from '@/api/department'
import { getEmployeeSimple } from '@/api/employees'
export default {
  props: {
    //   设置显示元素，默认为false
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 父组件传过来的点击元素
    nodeData: {
      type: Object,
      required: true
    }
  },

  data() {
    // 校验同一个部门下不能重名
    const validateName = async(rule, val, callback) => {
      const { depts } = await department()
      console.log('全部部门信息', depts)
      console.log('被点击的部门', this.nodeData)

      //   console.log(88, depts.filter(item => { return item.pid === this.nodeData.id }))
      //   // 筛选出同一个名字的数组
      //   const children = depts.filter(item => { return item.pid === this.nodeData.id })
      //   console.log('是否有重名', children.some(item => item.name === val))
      let isRepeat
      // 判断是否有id，有id的情况话，就是编辑
      if (this.formData.id) {
        isRepeat = depts.filter(item => item.pid === this.nodeData.pid).some(item => item.name === val && item.id !== this.nodeData.id)
        console.log(99, isRepeat)
      } else {
      // 无id的情况下，是新增
        isRepeat = depts.filter(item => item.pid === this.nodeData.id).some(item => item.name === val)
        console.log(isRepeat)
      }

      //   判断是否重名
      if (isRepeat) {
        callback(new Error('同一父部门下不能重名'))
      } else {
        callback()
      }
    }

    // 检查部门编码的过程同理
    const checkCodeRepeat = async(rule, val, callback) => {
      const { depts } = await department()

      let isRepeat
      if (this.formData.id) {
        // 编辑
        isRepeat = depts.some(item => item.code === val && item.id !== this.nodeData.id)
        console.log(55, isRepeat)
      } else {
        // 新增
        isRepeat = depts.some(item => item.code === val)
        console.log(isRepeat)
      }

      //   判断是否重名
      if (isRepeat) {
        callback(new Error('部门编码必须唯一'))
      } else {
        callback()
      }
    }

    return {
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        pid: ''
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          { max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],

        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' },
          { max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: checkCodeRepeat, trigger: 'blur' }
        ],

        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],

        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { trigger: 'blur', max: 300, message: '部门介绍要求1-50个字符' }]
      },
      employeeList: []
    }
  },

  // 初始化钩子函数
  async created() {
    this.employeeList = await getEmployeeSimple()
    console.log(this.employeeList)
  },

  // 部门负责人选择
  methods: {
    // 延迟失焦触发
    checkManager() {
      setTimeout(() => {
        this.$refs.addDept.validateField('manager')
      }, 100)
    },

    // 点击确定按钮后
    // 发送请求
    async btnOK() {
      // 校验
      await this.$refs.addDept.validate()
      // 发请求
      // 判断
      if (this.formData.id) {
        // 编辑
        await getDepartment(this.formData)
      } else {
        // 新增
        await addDepartment({
          ...this.formData,
          pid: this.nodeData.id
        })
      }

      // 提示用户
      this.$message.success('操作成功')
      // 页面需要更新
      this.$emit('addeparment')
      // 关闭弹窗
      // this.showDialog = false
      this.$emit('update:showDialog', false)
    },

    // 关闭窗口
    btnCancel() {
      this.formData = {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        pid: ''
      }
      // 1. 清理数据和校验错误
      this.$refs.addDept.resetFields()
      // 2.关闭弹窗
      this.$emit('update:showDialog', false)
    },

    // 加载表单详情，把它放进this.formData
    async companyDepartment(id) {
      console.log('加载表单详情')
      this.formData = await companyDepartment(id)
      console.log(this.formData)
    }

  }
}
</script>

<style>

</style>
